import time
from pylons import g
import pyleo.lib.helpers as h
import smtplib

class StandardPing:
    ''' Defines a standard trackback and relevant methods'''
    def __init__(self,argdict=None):
        ''' Instantiate with payload or empty '''
        self.allowed=['title','url','excerpt','blog_name']
        self.properties=['title','url','blog_name']
        self.data={}
        if argdict is not None:
            for key in argdict:
                self.__setitem__(key,argdict[key])
    def __setitem__(self,key,item):
        ''' set item just as if it is dictionary, but keys are limited'''
        if item is not None: self.data[key]=item
    def __getitem__(self,key):
        return self.data[key]
    def isValid(self):
        '''Boolean check on validity of payload content'''
        valid=1
        for key in self.data.keys(): 
                if key not in self.allowed: valid=0 
        if 'url' not in self.data.keys(): valid=0
        return valid
    def verify(self,myURL):
        ''' Parse the ping address and verify we (at myURL) have been pinged'''
        #not yet implemented, I want this inside the standard ping because it
        #might fit better with possible trackback ping header configs ...
        #need to make sure this is a GET
        req=urllib2.Request(myURL)
        req.add_header('User-Agent','Leonardo trackback verification')
        #note socket timeout set in provider init module ...
        try:fd=urllib2.urlopen(req)
        except IOError,e:
                return 0
        for line in fd.readlines():
                if myURL in line: return 1
        return
	
def add_trackback(params, resource):
    ''' Takes the ping, checks it, and then loads into storage '''
    ping=StandardPing(params)
    if not ping.isValid(): message='Invalid ping content'
    myURL=g.site_url+h.url_for()

    #we won't actuallly use this until we've logged a bit of experience
    #when we're happy, delete next line, and replace tmpMessage with
    #message if fail pingverify.
    tmpMessage=''
    if not ping.verify(myURL): 
        tmpMessage='Unable to verify source of trackback'
	    
    if message=='':
        existing_trackbacks = resource.get_annotations(atype='trackback')
        next_index = 0
        wait=0  # flag to throttle incoming trackbacks
        for trackback in existing_trackbacks:
            # Assume that trackbacks should not come more than one a minute
            # so if it's too recent warn the
            lastmod=trackback['last_modified']
            if lastmod:
                now=time.time()
                if (now-lastmod) < 60:
                    wait=1
            if int(trackback['index']) > next_index:
                next_index = int(trackback['index'])
                
        if not wait:
            next_index += 1
            new_trackback = resource.leof.enclosure("trackback", next_index)
            for key in ping:
	       if key in ping.properties: new_trackback.set_property(key,ping[key])
	       if 'excerpt' not in ping: 
	           new_trackback.set_content('__empty__', "txt")
	       else:
                   new_trackback.set_content(ping['excerpt'],'txt')
	       # hack to deal with no excerpt ...
	else:
            message='Trackback Throttle: Please resubmit trackback ping after one minute'

    messageTxt="New trackback received on %s\n Error response was %s\n (tmpMessage %s)"%(
            myURL,message,tmpMessage)

    mailBlogOwner(messageTxt)
        
    return message
              
def add_comment(params,resource):

    try:
        message=''
        comment_content = params["comment_content"]
        author_name     = params["author_name"]
        author_link     = params["author_link"]
    except KeyError,e:
        message='Not all comment content found [%s]'%str(e)

    myURL=g.site_url+h.url_for()

    messageTxt='New Comment received on %s'%myURL
    
    existing_comments = resource.get_annotations(atype="comment")
    next_index = 0
    for comment in existing_comments:
        if int(comment['index']) > next_index:
            next_index = int(comment['index'])
    next_index += 1
    
    new_comment = resource.leof.enclosure("comment", next_index)
    new_comment.set_content(comment_content, "txt")
    
    if author_name:
        new_comment.set_property("author_name", author_name)
	messageTxt+='Author Name: %s\n'%author_name
    if author_link:
        new_comment.set_property("author_link", author_link)
	messageTxt+="Author Link: %s\n"%author_link

    mailBlogOwner(messageTxt)
    
    return message
    
def mailBlogOwner(messageTxt):
    ''' If required, mail the blog owner '''
    debug=1
    if g.notify:
        try:
            server=smtplib.SMTP(g.SMTPserver)
            server.set_debuglevel(1)
            toaddr=g.authorEmail
            fromaddr="From: %s\n"% g.authorEmail
            message="To: %s\n" % g.authorEmail
            message+=fromaddr
            message+="Subject: Automatic message from leonardo"
            message+=messageTxt
            server.sendmail(fromaddr, toaddr, message)
            server.quit()
	except Exception,e:
            #we don't want it to fail with any messages in real life!
            if debug: 
                raise Exception,e
           

    